//
//  ST_UIButton+FW.swift
//  BTVideo
//
//  Created by DouLei on 2019/7/20.
//  Copyright © 2019 DouLei. All rights reserved.
//

import Foundation
import SDWebImage


extension UIButton{
    
    public func add_touch_up(insideTarget target:Any,action:Selector){
        self.addTarget(target, action: action, for: UIControl.Event.touchUpInside)
    }
    
    public func set_back_image_for_all_states(_ image: UIImage) {
        
        [.normal, .selected, .highlighted, .disabled].forEach {
            
            self.setBackgroundImage(image, for: $0)
        }
    }
    
    open func sd_setAllImage(with url:String,placeholderImageName:String? = nil){
        
        //        [UIControl.State.normal, UIControl.State.selected, UIControl.State.highlighted, UIControl.State.disabled].forEach {
        //
        //            let url = URL(string:url)
        //            var image:UIImage?
        //            if let name = placeholderImageName{
        //                image = UIImage.init(named: name)
        //            }
        //
        //            self.pin_setImage(from: url, for: $0, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image(), options: SDWebImageOptions.retryFailed, completed: nil)
        //
        //            self.pin_setImage(from: T##URL?, placeholderImage: T##UIImage?)
        //
        //        }
        var image:UIImage?
        if let name = placeholderImageName{
            image = UIImage.init(named: name)
        }
        self.pin_setImage(from: url.url, placeholderImage: image)
    }
    
    func adjust_to_vertical(spacing:CGFloat = 1.0)  {
        
        let imageSize = self.imageView?.size ?? CGSize.zero
        
        titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -imageSize.width, bottom: -(imageSize.height + spacing), right: 0)
        
        let titleSize = self.titleLabel?.size ?? CGSize.zero
        
        imageEdgeInsets = UIEdgeInsets.init(top: -(titleSize.height + spacing), left: 0, bottom: 0, right: -titleSize.width)
        
    }
    
    private(set) var lastTitleDict: [String:String]? {
        get {
            return objc_getAssociatedObject(self, &ST_AssociatedKeys.last_title_key) as? [String:String]
        }
        set(newValue) {
            objc_setAssociatedObject(self, &ST_AssociatedKeys.last_title_key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    private var activityView: UIActivityIndicatorView {
        get {
            if let actView = objc_getAssociatedObject(self, &ST_AssociatedKeys.activity_view_key) as? UIActivityIndicatorView{
                return actView
            }else{
                let actView = self.add_activity_view()
                self.activityView = actView
                return actView
            }
        }
        set(newValue) {
            objc_setAssociatedObject(self, &ST_AssociatedKeys.activity_view_key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    private func add_activity_view() ->UIActivityIndicatorView {
        
        let actView = UIActivityIndicatorView.init()
        self.addSubview(actView)
        
        actView.translatesAutoresizingMaskIntoConstraints = false
        
        let horizontalConstraint = NSLayoutConstraint(item: actView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
        
        let verticalConstraint = NSLayoutConstraint(item: actView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0)
        
        self.addConstraints([horizontalConstraint, verticalConstraint])
        
        return actView
    }
    
    
    
    // loading method
    public func loading(status:Bool = true){
        if status {
            
            if self.isEnabled == false {
                return
            }
            
            self.isEnabled = false
            
            var temDict = [String:String]()
            
            temDict.updateValue(self.title(for: .normal) ?? "", forKey: "normal")
            
            temDict.updateValue(self.title(for: .selected) ?? "", forKey: "selected")
            
            temDict.updateValue(self.title(for: .highlighted) ?? "", forKey: "highlighted")
            
            temDict.updateValue(self.title(for: .disabled) ?? "", forKey: "disabled")
            
            self.lastTitleDict = temDict
            
            self.setTitle("", for: .normal)
            self.setTitle("", for: .selected)
            self.setTitle("", for: .highlighted)
            self.setTitle("", for: .disabled)
            
            self.activityView.startAnimating()
        }else{
            
            if self.isEnabled {
                return
            }
            
            self.isEnabled = true
            
            self.setTitle( (self.lastTitleDict?["normal"]) ?? "", for: .normal)
            self.setTitle( (self.lastTitleDict?["selected"]) ?? "", for: .selected)
            self.setTitle( (self.lastTitleDict?["highlighted"]) ?? "", for: .highlighted)
            self.setTitle( (self.lastTitleDict?["disabled"]) ?? "", for: .disabled)
            
            self.activityView.stopAnimating()
            
        }
    }
    
}


extension CGAffineTransform{
    
    static func transform_from_rect(from source: CGRect, toRect destination: CGRect) -> CGAffineTransform {
        
        return CGAffineTransform.identity
            .translatedBy(x: destination.midX - source.midX, y: destination.midY - source.midY)
            .scaledBy(x: destination.width / source.width, y: destination.height / source.height)
    }
    
    
}
